const express = require('express')
const cookieSession = require('cookie-session')
// 登录检查
const loginMiddleware = require('./middleware/loginMiddleware')
const check = require('./middleware/check')

const app = express()
app.listen(3000)
app.use(express.static('www'))

// session
app.use(cookieSession({
  name: 'sessid',
  secret: 'fewfewfewklfjekfjelwfelwfewlfjekfewlfjewfewllfeejflw'
}))

// post接受
app.use(express.urlencoded({ extended: false }))
app.use(express.json())


// 登录
app.post('/login', loginMiddleware, (req, res) => {
  // 写入session保持状态
  req.session['username'] = req.body.username
  res.redirect('/admin/welcome')
})

app.use('/admin', check)

// 后台欢迎页
app.get('/admin/welcome', (req, res) => {

  res.send('welcome')
})

app.get('/logout',(req,res)=>{
  req.session['username'] = null;
  delete req.session['username']
  res.redirect('/login.html')
})


// 404页面
app.use((req, res) => {
  res.status(404).send('没有页面')
})